(function($, document, window) {
  'use strict';

  var ns = jfJQMAmobeeAds;
  
  function onPageShowLoadAds (e) {
    if (ns.getConfig('autoLoadAds', true)) {
      var $page = $(e.target);
      $(function() { //wait for domReady Event if this is the first call
        ns.sendAdServerRequest($page);
      });
    }
  }
  
  function onPageHideReset (e) {
    var $page = $(e.target);
    $page.find('.jfJQMAmobeeAd').empty();
    ns.resetPage($page);
  }

  var nsSendAdServerRequest = ns.sendAdServerRequest;
  ns.sendAdServerRequest = function($page, ads, responsemarkup) {
    $page = $page || $.mobile.activePage;
    nsSendAdServerRequest($page, ads, responsemarkup);
  };

  $(document).bind('jfJQMAmobeeAds:hideInterstitial', function() {
    $('.ui-header, .ui-footer').fixedtoolbar('updatePagePadding');
  });
  
  $("div:jqmData(role='page')").
      live('pageshow', onPageShowLoadAds).
      live('pagehide', onPageHideReset);

})(jQuery, document, window);